<?php
class MobDB {
	var $dbh;
	var $result;
	var $last_result;
	var $last_query;
	var $insert_id;
	var $col_info;
	var $num_rows;

	/**
	 * Connects to the database server and selects a database
	 * @param string $dbuser
	 * @param string $dbpassword
	 * @param string $dbname
	 * @param string $dbhost
	 */
	function MobDB($dbuser, $dbpassword, $dbname, $dbhost) {
		return $this->__construct($dbuser, $dbpassword, $dbname, $dbhost);
	}

	function __construct($dbuser, $dbpassword, $dbname, $dbhost) {
		$this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword, true);
		if (!$this->dbh) {
			$this->bail("
				<h1>Error establishing a database connection</h1>
				<p>This either means that the username and password information in your <code>sp-config.php</code> file is incorrect or we can't contact the database server at <code>$dbhost</code>. This could mean your host's database server is down.</p>
				<ul>
					<li>Are you sure you have the correct username and password?</li>
					<li>Are you sure that you have typed the correct hostname?</li>
					<li>Are you sure that the database server is running?</li>
				</ul>
				");
			return;
		}

		$this->select($dbname);

		//Set UTF8
		mysql_query("SET NAMES 'utf8'");		
	}

	function select($db) {
		if (!@mysql_select_db($db, $this->dbh)) {
			$this->bail("
				<h1>Can&#8217;t select database</h1>
				<p>We were able to connect to the database server (which means your username and password is okay) but not able to select the <code>$db</code> database.</p>
				<ul>
				<li>Are you sure it exists?</li>
				<li>Does the user <code>".DB_USER."</code> have permission to use the <code>$db</code> database?</li>
				<li>On some systems the name of your database is prefixed with your username, so it would be like username_wordpress. Could that be the problem?</li>
				</ul>
				");
			return;
		}
	}

	function escape($string) {
		if (get_magic_quotes_gpc())
			$string = stripslashes($string);

		return @mysql_real_escape_string( $string );
	}
	
	function bail($message) { // Just wraps errors in a nice header and footer
		echo $message;
	}
	
	/*
	 * Quereis 
	 */
	function query($query) {
		//Last Query
		$this->last_query = $query;

		//Execute the Query
		$this->result = mysql_query($query, $this->dbh);
		
		//Check if the query modify any row
		if ( preg_match("/^\\s*(insert|delete|update|replace) /i",$query) ) {
			$this->rows_affected = mysql_affected_rows($this->dbh);

			// Take note of the insert_id
			if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
				$this->insert_id = mysql_insert_id($this->dbh);
			}

			// Return number of rows affected
			$return_val = $this->rows_affected;
		} else {
			$i = 0;
			while ($i < @mysql_num_fields($this->result)) {
				$this->col_info[$i] = @mysql_fetch_field($this->result);
				$i++;
			}

			$num_rows = 0;
			$this->last_result = array();
			while ( $row = @mysql_fetch_object($this->result) ) {
				$this->last_result[$num_rows] = $row;
				$num_rows++;
			}
			$this->num_rows = $num_rows;
			
			//Free the old result
			if ($this->num_rows > 0 && isset($this->result))
				mysql_free_result($this->result);

			
			// Return number of rows selected
			$return_val = $this->num_rows;
		}

		return $return_val;
	}
	
	/**
	 * Insert an array of data into a table
	 * @param string $table WARNING: not sanitized!
	 * @param array $data should not already be SQL-escaped
	 * @return mixed results of $this->query()
	 */
	function insert($table, $data) {
		$data   = add_magic_quotes($data);
		$fields = array_keys($data);
		return $this->query("INSERT INTO $table (`" . implode('`,`',$fields) . "`) VALUES ('".implode("','",$data)."')");
	}
	
	function get_last_insert_id() {
		return mysql_insert_id();
	}

	/**
	 * Update a row in the table with an array of data
	 * @param string $table WARNING: not sanitized!
	 * @param array $data should not already be SQL-escaped
	 * @param array $where a named array of WHERE column => value relationships.  Multiple member pairs will be joined with ANDs.  WARNING: the column names are not currently sanitized!
	 * @return mixed results of $this->query()
	 */
	function update($table, $data, $where){
		$data = add_magic_quotes($data);
		$bits = $wheres = array();
		foreach ( array_keys($data) as $k )
			$bits[] = "`$k` = '$data[$k]'";

		if ( is_array( $where ) )
			foreach ( $where as $c => $v )
				$wheres[] = "$c = '" . $this->escape( $v ) . "'";
		else
			return false;

		return $this->query( "UPDATE $table SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres ) . ' LIMIT 1' );
	}
}

if ( !isset($mobdb) )
	$mobdb = new MobDB(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
?>
